package com.quanyan.stadium.service.impl;

import com.quanyan.club.entity.RespClubMemberBaseInfo;
import com.quanyan.club.entity.RespClubPlainInfo;
import com.quanyan.club.mq.ClubMedalMsg;
import com.quanyan.club.service.ClubOpenService;
import com.quanyan.comment.enums.TaskEnum;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.constants.MqConstants;
import com.quanyan.common.enums.SysClubMedalConditionEnum;
import com.quanyan.common.enums.SysUserMedalConditionEnum;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.messagepush.enums.IdType;
import com.quanyan.messagepush.enums.MsgType;
import com.quanyan.mq.client.QcMsgClient;
import com.quanyan.mq.client.reqeust.MqRequestMsg;
import com.quanyan.mq.client.response.MqResponse;
import com.quanyan.stadium.api.req.ReqUserRadarChart;
import com.quanyan.stadium.api.resp.RespUserRadarChart;
import com.quanyan.stadium.biz.BizPKEventDao;
import com.quanyan.stadium.biz.redis.UserGameScheduleCacheDao;
import com.quanyan.stadium.component.pushMsg.MsgPush;
import com.quanyan.stadium.component.pushMsg.StadiumMsgModel;
import com.quanyan.stadium.constants.GameConstants;
import com.quanyan.stadium.entity.TbPKEvent;
import com.quanyan.stadium.entity.TbPoints;
import com.quanyan.stadium.entity.vo.*;
import com.quanyan.stadium.enums.PkEventStatusEnum;
import com.quanyan.stadium.service.*;
import com.quanyan.stadium.service.commonComponent.BaseService;
import com.quanyan.stadium.service.commonComponent.ConfigService;
import com.quanyan.stadium.utils.GameCategoryScoreUtils;
import com.quanyan.stadium.utils.StringUtils;
import com.quanyan.user.mq.UserMedalMsg;
import com.quanyan.user.mq.UserTaskMsg;
import com.quanyan.user.response.RespUserInfoBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * PK赛service
 * Created by lei.w on 16/6/23.
 */
@Service
public class PKEventServiceImpl implements PKEventService {

    private static final Logger logger = LoggerFactory.getLogger(PKEventServiceImpl.class);

    @Autowired
    private BizPKEventDao bizPKEventDao;
    @Autowired
    private PointsService pointsService;
    @Autowired
    private BaseService baseService;
    @Autowired
    private RadarChartService radarChartService;
    @Autowired
    private QcMsgClient qcMsgClient;
    @Autowired
    UserGameScheduleCacheDao userGameScheduleCacheDao;
    @Autowired
    private GradeIntegralService gradeIntegralService;
    @Autowired
    ClubOpenService clubOpenService;
    @Autowired
    MsgPush msgPush;
    @Autowired
    ConfigService configService;

    @Override
    public PKEventVo createPKEvent(PKEvent pkEvent) throws BizException{

        PKEventVo pkEventVo;
        try {
            logger.info("createPKEvent reqPKEvent:"+pkEvent.toString());

            // 个人pk时填写接收用户信息
            List<Integer> list = new ArrayList<Integer>();
            list.add(pkEvent.getFormId());
            list.add(pkEvent.getToId());
            if (pkEvent.getType().byteValue() == GameConstants.TEAM_TYPE_PERSON){
                Map<Integer, RespUserInfoBase> map = baseService.queryUserMsg(list);
                User user = new User();
                if (ObjectUtil.isNotObjectEmpty(map.get(pkEvent.getFormId()))) {
                    BeanUtils.copyProperties(map.get(pkEvent.getFormId()), user);
                }
                pkEvent.setFromUser(user);

                user = new User();
                if (ObjectUtil.isObjectEmpty(map.get(pkEvent.getToId()))) {
                    throw new BizException("to user info query null.");
                }

                BeanUtils.copyProperties(map.get(pkEvent.getToId()), user);
                pkEvent.setToUser(user);

            } else if (pkEvent.getType().byteValue() == GameConstants.TEAM_TYPE_CLUB) {
                Map<Integer, RespClubPlainInfo>  map = baseService.queryClubMsg(list);
                pkEvent.setFromClub(map.get(pkEvent.getFormId()));
                RespClubPlainInfo toClub = map.get(pkEvent.getToId());
                if (ObjectUtil.isObjectEmpty(toClub)) {
                    throw new BizException("club info query null");
                }
                pkEvent.setToClub(toClub);
                User user = new User();
                user.setUid(pkEvent.getUid());
                pkEvent.setFromUser(user);
            }

            pkEventVo = pkEvent;
            if (ObjectUtil.isNotObjectEmpty(pkEvent.getId()) && pkEvent.getId().intValue() != 0) {
                logger.info("createPKEvent updatePKEvent pkEventVo:"+pkEventVo.toString());
                bizPKEventDao.updatePKEvent(pkEventVo);

            } else {
                // 数据持久化
                pkEventVo.setId(bizPKEventDao.createPKEvent(pkEvent));
                // 消息推送
                pushPKMessage(pkEventVo, MsgType.JUMP_MSG, 1);
            }
        } catch (Exception e) {
            logger.error("createPKEvent is failed. e:", e);
            throw new BizException("send pk failed");
        }

        return pkEventVo;
    }

    @Override
    public List<PKEventVo> queryUserPKList(Integer uid, Integer status) {
        if (ObjectUtil.isObjectEmpty(uid, status)) {
            logger.info("queryUserPKList param uid or status is null. uid:"+ uid+" ststus:"+status);
        }

        return batchTbPkEventChange(GameConstants.TEAM_TYPE_PERSON.intValue(), uid,  bizPKEventDao.queryUserPKList(uid, status));
    }

    @Override
    public List<PKEventVo> queryUserCreatePKList(Integer id, Integer status, Integer type) {
        if (ObjectUtil.isObjectEmpty(id, status,type)) {
            logger.info("queryUserCreatePKList param uid or status is null. uid:"+ id+" ststus:"+status);
            return Collections.emptyList();
        }

        List<TbPKEvent>  tbPKEventList;
        if (type.intValue() == GameConstants.TEAM_TYPE_PERSON) {
            tbPKEventList = bizPKEventDao.queryUserCreatePKList(id, status, type);
        } else {
            tbPKEventList = bizPKEventDao.queryCludCreatePKList(id,status,type);
        }
        // 获取用户创建PK信息

        if (tbPKEventList == null || tbPKEventList.size() == 0) {
            logger.info("queryUserCreatePKList tbPKEventList is null. uid:"+ id.intValue());
            return Collections.emptyList();
        }

        return batchTbPkEventChange(type, id, tbPKEventList);
    }

    @Override
    public List<PKEventVo> queryUserReceivePKList(Integer id, Integer status, Integer type) {
        if (ObjectUtil.isObjectEmpty(id, status,type)) {
            logger.info("queryUserReceivePKList param uid or status is null. uid:"+ id+" ststus:"+status);
            return Collections.emptyList();
        }

        List<TbPKEvent>  tbPKEventList = null;
        try {
            if (type.byteValue() == GameConstants.TEAM_TYPE_PERSON) {
                tbPKEventList = bizPKEventDao.queryUserReceivePKList(id, status, type);
            } else if (type.byteValue() == GameConstants.TEAM_TYPE_CLUB) {
                tbPKEventList = bizPKEventDao.queryCludReceivePKList(id, status, type);
            }
        } catch (Exception ex){
            logger.error("queryUserInfo getClubBaseInfoByUserId is failed. ex:", ex);
        }

        return batchTbPkEventChange(type, id, tbPKEventList);
    }

    @Override
    public PKEventVo queryUserNewestCreatePK(Integer uid, Integer categoryId) {

        if (ObjectUtil.isObjectEmpty(uid, categoryId)) {
            return null;
        }

        return tbPkEventChangeReqPKEventVo(bizPKEventDao.queryUserNewestCreatePK(uid, categoryId));
    }

    @Override
    public PKEventVo getPKInfoById(Integer pkid) {
        PKEventVo pkEventVo = null;
        if (ObjectUtil.isObjectEmpty(pkid)) {
            return pkEventVo;
        }

        // 查询用户信息
        TbPKEvent tbPKEvent = bizPKEventDao.getPKInfoById(pkid);
        pkEventVo = tbPkEventChangeReqPKEventVo(tbPKEvent);
        if (tbPKEvent.getType().byteValue() == GameConstants.TEAM_TYPE_CLUB) {
            pkEventVo.setFromClub(baseService.queryClubMsg(tbPKEvent.getFromClubId()));
            pkEventVo.setToClub(baseService.queryClubMsg(tbPKEvent.getToClubId()));
        }

        if (tbPKEvent.getType().byteValue() == GameConstants.TEAM_TYPE_PERSON) {
            List<Integer> uidList = new ArrayList<>();
            uidList.add(tbPKEvent.getFromUid());
            uidList.add(tbPKEvent.getToUid());

            Map<Integer, RespUserInfoBase>  map = baseService.queryUserMsg(uidList);
            User user = new User();
            BeanUtils.copyProperties(map.get(tbPKEvent.getFromUid()), user);
            pkEventVo.setFromUser(user);
            user = new User();
            BeanUtils.copyProperties(map.get(tbPKEvent.getToUid()), user);
            pkEventVo.setToUser(user);
        }

        // 特殊处理（PK状态为已接受且PK已进行1个小时则Pk状态设置为已结束） begin
        long begenTime = pkEventVo.getBeginTime().longValue() + 3600000L;
        if (pkEventVo.getStatus().equals(PkEventStatusEnum.PK_STATUS_AGREE.getId()) && begenTime < System.currentTimeMillis()) {
            logger.info("getPKInfoById updatePKStatus pk status update pk id:"+pkEventVo.getId()+" pkEventVo.getBeginTime:"+ begenTime);
            updatePKStatus(pkEventVo.getId(), PkEventStatusEnum.PK_STATUS_END.getId());
            pkEventVo.setStatus(PkEventStatusEnum.PK_STATUS_END.getId());
        }
        // end

        try {
            // 设置用户雷达图
            RespUserRadarChart userRadarChart = radarChartService.userRadarChart(new ReqUserRadarChart(pkEventVo.getFromUser().getUid(), tbPKEvent.getCategoryId()));
            if (null != userRadarChart){
                pkEventVo.setForomUserRadarChart(userRadarChart);
            }
            userRadarChart = radarChartService.userRadarChart(new ReqUserRadarChart(pkEventVo.getToUser().getUid(), tbPKEvent.getCategoryId()));
            if (null != userRadarChart){
                pkEventVo.setToUserRadarChart(userRadarChart);
            }
        } catch (Exception e) {
            logger.error("getPKInfoById is null. e:", e);
        }

        return pkEventVo;
    }

    @Override
    public PKEventVo getPKInfoByIdAndUid(Integer uid, Integer pkid) {
        PKEventVo pkEventVo =  getPKInfoById (pkid);
        if (ObjectUtil.isObjectEmpty(pkEventVo)) {
            return pkEventVo;
        }

        // pk状态为已录完时，查询pk结果
        if (pkEventVo.getStatus().intValue() == PkEventStatusEnum.PK_STATUS_ENTRY.getId()) {
            pkEventVo.setPkResultVo(bizPKEventDao.queryPkResultByUidAndPkid(uid, pkid));
        }

        return pkEventVo;
    }

    @Override
    public boolean updatePKStatus(PKEventVo pkEventVo) {
        PKEventVo pkEventVo1 = getPKInfoById(pkEventVo.getId());
        if (null == pkEventVo1){
            return false;
        }

        pkEventVo1.setStatus(pkEventVo.getStatus());
        boolean flag = bizPKEventDao.updatePKStatusById(pkEventVo.getId(), pkEventVo.getStatus(), pkEventVo.getBeginTime()) > 0 ? true : false;

        try {
            // 消息推送
            if (pkEventVo.getStatus().equals(PkEventStatusEnum.PK_STATUS_AGREE.getId())) {
                pushPKMessage(pkEventVo1,MsgType.JUMP_MSG, 0);


                pkEventVo1.setStatus(pkEventVo.getStatus());
                pkEventVo1.setBeginTime(pkEventVo.getBeginTime());

                if (pkEventVo1.getType().byteValue() == GameConstants.TEAM_TYPE_PERSON.byteValue()) {
                    // 用户勋章消息
                    userMedalMessage(pkEventVo1);

                    // 通知用户任务中心   taskType 1: 发起的PK
                    pushPkMessageTaskCenter(pkEventVo1.getFromUser().getUid(), 1);
                } else {
                    // 俱乐部勋章消息
                    clubMedalMessage(pkEventVo1);
                }

            } else if (pkEventVo.getStatus().equals(PkEventStatusEnum.PK_STATUS_REFUSE.getId())) {
                pushPKMessage(pkEventVo1,MsgType.NOTIFY_MSG, 0);
            }
        } catch (Exception e) {
            logger.error("updatePKStatus additional business failure. e:", e);
        }

        logger.info("updatePKStatus update status flag:" + flag);

        return flag;
    }

    public boolean updatePKStatus(Integer id, Integer status) {
        return bizPKEventDao.updatePKStatusById(id, status) > 0 ? true : false;
    }

    @Override
    public void entryPKResult(PKResultVo pkResultVo, PKEventVo pkEventVo) throws BizException{

        try {
            pkResultVo.setId(pkEventVo.getId());

            // 修改PK状态为已录完
            updatePKStatus(pkResultVo.getId(), PkEventStatusEnum.PK_STATUS_ENTRY.getId());

            // pk积分信息录入--pk结果表
            bizPKEventDao.entryPKResult(pkResultVo);

        } catch (Exception e) {
            logger.error("entryPKResult is failed. e:", e);
        }

    }

    @Override
    public void pkResultConfirm(PKResultVo pkResultVo, PKEventVo pkEventVo) {

        if (pkResultVo.getIsAgree().intValue() == 0) {
            // 修改PK状态为已录完
            updatePKStatus(pkResultVo.getId(), PkEventStatusEnum.PK_STATUS_REFUSE.getId());
            logger.info("pkResultConfirm  uid:"+pkResultVo.getUid() +" The results do not agree with pk.");
            return;
        }

        // 修改PK状态为已录完
        updatePKStatus(pkResultVo.getId(), PkEventStatusEnum.PK_STATUS_CONFIRM.getId());

        // 俱乐部消息不推送
        if (pkEventVo.getType().byteValue() == GameConstants.TEAM_TYPE_CLUB) {
            return;
        }

        List<PKResultVo> resultVoList = bizPKEventDao.queryPkResultByPkid(pkResultVo.getId());
        Integer fromUid = pkEventVo.getFromUser().getUid();
        Integer toUid = pkEventVo.getToUser().getUid();
        int fromZ = 0;
        int toZ = 0;
        for (PKResultVo pkR : resultVoList) {
            if (pkR.getUid().equals(fromUid)) {
                if (pkR.getPkResult() == GameConstants.PK_RESULT_WIN) {
                    fromZ = 1;
                    toZ = 2;
                } else if (fromZ == GameConstants.PK_RESULT_LOSE) {
                    fromZ = 2;
                    toZ = 1;
                } else {
                    fromZ = 1;
                    toZ = 1;
                }
            } else {
                if (pkR.getPkResult() == GameConstants.PK_RESULT_WIN) {
                    fromZ = 2;
                    toZ = 1;
                } else if (pkR.getPkResult() == GameConstants.PK_RESULT_LOSE) {
                    fromZ = 1;
                    toZ = 2;
                } else {
                    fromZ = 1;
                    toZ = 1;
                }
            }

        }

        pushUserPKResultMessage(pkEventVo.getId(), fromUid, toUid, pkEventVo.getCategoryId(), fromZ);

        // 用户每天第一次PK时记录积分
        if (!userGameScheduleCacheDao.isUserPkScoreEntryFlag(fromUid)) {

            // 更新用户栏目积分
            Double score = GameCategoryScoreUtils.getUserCategoryScore(1, 1, 2, fromZ, new Date(pkEventVo.getBeginTime()));
            modifyUserScore(fromUid, score.intValue(), pkEventVo.getCategoryId());

            // 通知用户任务中心   taskType 2: 已完成的PK
            pushPkMessageTaskCenter(fromUid, 2);
        }

        // 用户每天第一次PK时记录积分
        if (!userGameScheduleCacheDao.isUserPkScoreEntryFlag(toUid)) {
            // 更新用户栏目积分
            Double score = GameCategoryScoreUtils.getUserCategoryScore(1, 1, 2, toZ, new Date(pkEventVo.getBeginTime()));
            modifyUserScore(toUid, score.intValue(), pkEventVo.getCategoryId());

            // 通知用户任务中心   taskType 2: 已完成的PK
            pushPkMessageTaskCenter(toUid, 2);
        }

        // 用户勋章消息
        if (pkEventVo.getType().byteValue() == GameConstants.TEAM_TYPE_PERSON.byteValue()) {
            userMedalMessage(pkEventVo);
        } else {
            clubMedalMessage(pkEventVo);
        }
    }

    private void modifyUserScore(Integer uid, int score, int categoryId) {
        // pk胜利者积分录入
        TbPoints tbPoints = new TbPoints();
        tbPoints.setCategoryId(categoryId);
        tbPoints.setUid(uid);
        tbPoints.setScore(score);

        boolean flag = pointsService.entryUserPoints(tbPoints);
        logger.info("entryPKResult winner user id:"+tbPoints.getUid()+" score:"+tbPoints.getScore()+" flag:"+ flag);
    }

    private List<PKEventVo> batchTbPkEventChange(Integer type, Integer id, List<TbPKEvent> tbPKEventList) {
        if (tbPKEventList == null || tbPKEventList.size() == 0) {
            logger.info("queryUserReceivePKList tbPKEventList is null. id:"+ id.intValue());
            return Collections.emptyList();
        }

        Set<Integer> idSet = new HashSet<>();
        List<PKEventVo> pkEventVoList = new ArrayList<>();
        Map<Integer, RespUserInfoBase>  map = Collections.emptyMap();
        Map<Integer, RespClubPlainInfo>  mapClub = Collections.emptyMap();
        if (type.byteValue() == GameConstants.TEAM_TYPE_PERSON) {
            for (TbPKEvent tbPKEvent : tbPKEventList) {
                idSet.add(tbPKEvent.getFromUid());
                idSet.add(tbPKEvent.getToUid());
            }
            map = baseService.queryUserMsg(new ArrayList<>(idSet));


        } else if (type.byteValue() == GameConstants.TEAM_TYPE_CLUB) {
            for (TbPKEvent tbPKEvent : tbPKEventList) {
                idSet.add(tbPKEvent.getFromClubId());
                idSet.add(tbPKEvent.getToClubId());
            }
            mapClub = baseService.queryClubMsg(new ArrayList<Integer>(idSet));
        }

        // 查询俱乐部信息
        for (TbPKEvent tbPKEvent : tbPKEventList) {
            PKEventVo pkEventVo = tbPkEventChangeReqPKEventVo(tbPKEvent);
            if (type.byteValue() == GameConstants.TEAM_TYPE_CLUB) {

                // 用户信息为空时不返回当前PK
                if (ObjectUtil.isObjectEmpty(mapClub.get(tbPKEvent.getFromClubId()), mapClub.get(tbPKEvent.getToClubId()))) {
                    continue;
                }

                pkEventVo.setFromClub(mapClub.get(tbPKEvent.getFromClubId()));
                pkEventVo.setToClub(mapClub.get(tbPKEvent.getToClubId()));
            } else if (type.byteValue() == GameConstants.TEAM_TYPE_PERSON){

                // 用户信息为空时不返回当前PK
                if (ObjectUtil.isObjectEmpty(map.get(tbPKEvent.getFromUid()), map.get(tbPKEvent.getToUid()))) {
                    continue;
                }

                User user = new User();
                user.setScore(pointsService.getPointsByCategoryIdAndUserIds(tbPKEvent.getFromUid(), tbPKEvent.getCategoryId()).doubleValue());
                user.setGrade(gradeIntegralService.getUserGradeInfo(tbPKEvent.getFromUid(), tbPKEvent.getCategoryId()).getGrade());
                BeanUtils.copyProperties(map.get(tbPKEvent.getFromUid()), user);
                pkEventVo.setFromUser(user);
                user = new User();
                user.setScore(pointsService.getPointsByCategoryIdAndUserIds(tbPKEvent.getToUid(), tbPKEvent.getCategoryId()).doubleValue());
                user.setGrade(gradeIntegralService.getUserGradeInfo(tbPKEvent.getToUid(), tbPKEvent.getCategoryId()).getGrade());
                BeanUtils.copyProperties(map.get(tbPKEvent.getToUid()), user);
                pkEventVo.setToUser(user);
            }

            // 特殊处理
            checkPkStatusAndProcess(pkEventVo, id);

            pkEventVoList.add(pkEventVo);
        }

        // 查询用户信息
        logger.info("batchTbPkEventChange PKEventVoList size:"+ pkEventVoList.size() +" result:" + pkEventVoList +" id:"+ id);

        return pkEventVoList;
    }

    private PKEventVo tbPkEventChangeReqPKEventVo(TbPKEvent tbPKEvent) {
        PKEventVo record = null;
        if (tbPKEvent == null) {
            return record;
        }

        record = new PKEventVo();
        record.setId(tbPKEvent.getId());
        record.setAddress(tbPKEvent.getAddress());
        record.setGameSystem(tbPKEvent.getGameSystem());
        record.setCategoryId(tbPKEvent.getCategoryId());
        record.setPayType(tbPKEvent.getPayType());
        record.setType(tbPKEvent.getType());
        if (null != tbPKEvent.getBeginTime()) {
            record.setBeginTime(tbPKEvent.getBeginTime().getTime());
        } else {
            record.setBeginTime(0L);
        }
        if (null != tbPKEvent.getBeginTime1()) {
            record.setBeginTime1(tbPKEvent.getBeginTime1().getTime());
        }
        if (null != tbPKEvent.getBeginTime2()) {
            record.setBeginTime2(tbPKEvent.getBeginTime2().getTime());
        }
        if (null != tbPKEvent.getBeginTime3()) {
            record.setBeginTime3(tbPKEvent.getBeginTime3().getTime());
        }

        record.setStatus(tbPKEvent.getStatus());
        record.setCreateTime(tbPKEvent.getCreateTime());
        record.setUpdateTime(tbPKEvent.getUpdateTime());
        record.setMessage(StringUtils.stringNullChange(tbPKEvent.getMessage()));
        logger.info("repPKEventVoChangeTbPkEvent record id:"+ record.getId());
        return record;
    }

    public void pushPkMessageTaskCenter(Integer uid, Integer taskType) {
        UserTaskMsg userTaskMsg = new UserTaskMsg();
        userTaskMsg.setUid(uid);
        if (taskType.intValue() == 1) {
            userTaskMsg.setTaskId(TaskEnum.TASK_ENUM__COME_PK.getId());
        } else {
            userTaskMsg.setTaskId(TaskEnum.TASK_ENUM__GO_PK.getId());
        }
        MqRequestMsg mqRequestMsg = new MqRequestMsg();
        mqRequestMsg.setTopic(Constants.MQ_TOPIC_TASK_TOPIC);
        mqRequestMsg.setTag(Constants.MQ_TOPIC_TASK_TAG);
        StringBuilder sb = new StringBuilder();
        sb.append(Constants.MQ_TOPIC_TASK_TOPIC).append("_PK_").append(uid.intValue()).append(System.currentTimeMillis());
        mqRequestMsg.setMsgId(sb.toString()); //msgId号.
        mqRequestMsg.setFlag(0);
        mqRequestMsg.setBody(ObjectUtil.toByteArray(userTaskMsg));
        qcMsgClient.syncSend(mqRequestMsg);
    }

    public void pushUserPKResultMessage(Integer pkid, Integer fromUid, Integer toUid, Integer categoryId, Integer result) {

        // 报文封装
        StadiumNotifyMsg stadiumNotifyMsg = new StadiumNotifyMsg();
        stadiumNotifyMsg.setFromUid(fromUid);
        stadiumNotifyMsg.setToUid(toUid);
        stadiumNotifyMsg.setCategoryId(categoryId);
        stadiumNotifyMsg.setMsgType(GameConstants.STADIUM_TAG_USER_PK_GAME_COLLECT);
        stadiumNotifyMsg.setPkResult(result);
        // msg封装
        MqRequestMsg mqRequestMsg = new MqRequestMsg();
        mqRequestMsg.setTopic(GameConstants.STADIUM_TOPIC_ROUND);
        mqRequestMsg.setTag(GameConstants.STADIUM_TOPIC_ROUND_RECORD);
        StringBuilder sb = new StringBuilder();
        sb.append(GameConstants.STADIUM_TOPIC_ROUND).append("_PK_").append(pkid.intValue()).append(System.currentTimeMillis());
        mqRequestMsg.setMsgId(sb.toString());
        mqRequestMsg.setFlag(0);
        mqRequestMsg.setBody(ObjectUtil.toByteArray(stadiumNotifyMsg));
        qcMsgClient.syncSend(mqRequestMsg);
    }

    private void pushPKMessage(PKEventVo pkEventVo, MsgType msgType, Integer postType){
        try {
            List<Integer> uids = new ArrayList<>();
            StadiumMsgModel stadiumMsgModel = new StadiumMsgModel();

            // 设置推送消息的接收用户
            String body;
            Map<String, Object> map = new HashMap<>();
            if (pkEventVo.getStatus().equals(PkEventStatusEnum.PK_STATUS_CREATE.getId())) {
                stadiumMsgModel.setIdType(IdType.STADIUM_PK_GAME_TO_PAGE);
                if (pkEventVo.getType().byteValue() == GameConstants.TEAM_TYPE_PERSON) {
                    uids.add(pkEventVo.getToUser().getUid());

                    body = pkEventVo.getFromUser().getNickName()+ configService.getProperty("pk.create.person.body", "向你发起了PK");
                    // 客户端需要参数
                    map.put("pkType", 2);
                } else{
                    List<RespClubMemberBaseInfo> respClubMemberBaseInfos = clubOpenService.getClubAdmins(pkEventVo.getToClub().getClubId());
                    if (null == respClubMemberBaseInfos || respClubMemberBaseInfos.size() == 0) {
                        return;
                    }

                    for (RespClubMemberBaseInfo clubMemberBaseInfo : respClubMemberBaseInfos) {
                        uids.add(clubMemberBaseInfo.getUid());
                    }

                    StringBuilder sb = new StringBuilder();
                    sb.append(pkEventVo.getFromClub().getClubName());
                    sb.append(configService.getProperty("pk.create.clud.body.before", "俱乐部向你所在的"));
                    sb.append(pkEventVo.getToClub().getClubName());
                    sb.append(configService.getProperty("pk.create.clud.body.rear", "俱乐部发起了PK"));

                    body = sb.toString();

                    // 客户端需要参数
                    map.put("pkType", 3);
                }
            } else {
                stadiumMsgModel.setIdType(IdType.STADIUM_PK_GAME_DETAIL_PAGE);
                if (pkEventVo.getType().byteValue() == GameConstants.TEAM_TYPE_PERSON) {
                    uids.add(pkEventVo.getFromUser().getUid());
                } else if (pkEventVo.getType().byteValue() == GameConstants.TEAM_TYPE_CLUB){

                    List<RespClubMemberBaseInfo> respClubMemberBaseInfos = clubOpenService.getClubAdmins(pkEventVo.getFromClub().getClubId());
                    if (null == respClubMemberBaseInfos || respClubMemberBaseInfos.size() == 0) {
                        return;
                    }

                    for (RespClubMemberBaseInfo clubMemberBaseInfo : respClubMemberBaseInfos) {
                        uids.add(clubMemberBaseInfo.getUid());
                    }
                }

                if (MsgType.JUMP_MSG.equals(msgType)) {
                    body = configService.getProperty("pk.notify.agree", "您发起的PK赛对方已同意");
                } else {
                    body = configService.getProperty("pk.notify.refuse", "您发起的PK赛对方已拒绝，本次PK已取消");
                }
            }

            map.put("original", 1);

            // 设置消息标题、 消息体
            stadiumMsgModel.setAlertTitle(configService.getProperty("pk.alert.title", "百灵鸟"));
            stadiumMsgModel.setAlertBody(configService.getProperty("pk.event.push.title", "赛事消息")+": "+body);
            stadiumMsgModel.setMsgTitle(body);
            stadiumMsgModel.setToUidList(uids);
            stadiumMsgModel.setMsgType(msgType);

            map.put("id",pkEventVo.getId());
            map.put("postType", postType);

            stadiumMsgModel.setParams(map);

            msgPush.pushMessageOperate(stadiumMsgModel);
        } catch (Exception e) {
            logger.error("pushPKMessage is  failed. e:", e);
        }
    }

    private boolean checkBeginTime(Long... beginTimes) {

        long beginTime = 0L;

        for (Long bt : beginTimes){
            if (ObjectUtil.isNotObjectEmpty(bt) && beginTime < bt.longValue()) {
                beginTime = bt.longValue();
            }
        }

        return beginTime < System.currentTimeMillis() ?  true : false;
    }

    private void userMedalMessage(PKEventVo pkEventVo) {
        try {

            // 俱乐部消息不推送
            if (pkEventVo.getType().byteValue() == GameConstants.TEAM_TYPE_CLUB) {
                return;
            }

            logger.info("userMedalMessage pkEventVo:"+ pkEventVo.toString());

            Integer medalId;
            // 消息推送只支持足篮网羽
            if (GameConstants.CATEGORY_ID_FOOTBALL == pkEventVo.getCategoryId().intValue()) {
                medalId = pkEventVo.getStatus().equals(PkEventStatusEnum.PK_STATUS_AGREE.getId()) ?
                        SysUserMedalConditionEnum.FOOTBALL_CHALLENGER.getId():SysUserMedalConditionEnum.FOOTBALL_CONQUEROR.getId();
            } else if (GameConstants.CATEGORY_ID_BASKETBALL == pkEventVo.getCategoryId().intValue()) {
                medalId = pkEventVo.getStatus().equals(PkEventStatusEnum.PK_STATUS_AGREE.getId()) ?
                        SysUserMedalConditionEnum.BASKETBALL_CHALLENGER.getId():SysUserMedalConditionEnum.BASKETBALL_CONQUEROR.getId();
            } else if (GameConstants.CATEGORY_ID_TENNIS == pkEventVo.getCategoryId().intValue()) {
                medalId = pkEventVo.getStatus().equals(PkEventStatusEnum.PK_STATUS_AGREE.getId()) ?
                        SysUserMedalConditionEnum.TENNIS_CHALLENGER.getId():SysUserMedalConditionEnum.TENNIS_CONQUEROR.getId();
            } else if (GameConstants.CATEGORY_ID_BADMINTON == pkEventVo.getCategoryId().intValue()) {
                medalId = pkEventVo.getStatus().equals(PkEventStatusEnum.PK_STATUS_AGREE.getId())  ?
                        SysUserMedalConditionEnum.BADMINTON_CHALLENGER.getId() : SysUserMedalConditionEnum.BADMINTON_CONQUEROR.getId();
            } else {
                return;
            }

            Integer uid = pkEventVo.getFromUser().getUid();
            if (pkEventVo.getStatus().equals(PkEventStatusEnum.PK_STATUS_CONFIRM.getId())) {
                List<PKResultVo> pkResultVoList = bizPKEventDao.queryPkResultByPkid(pkEventVo.getId());
                for (PKResultVo pkResultVo : pkResultVoList) {
                    if (GameConstants.PK_RESULT_WIN == pkResultVo.getPkResult().intValue()) {
                        uid = pkResultVo.getUid();
                    } else if (GameConstants.PK_RESULT_LOSE == pkResultVo.getPkResult().intValue()) {
                        uid = pkEventVo.getFromUser().getUid().equals(pkResultVo.getUid()) ? pkEventVo.getFromUser().getUid() : pkEventVo.getToUser().getUid();
                    } else if (GameConstants.PK_RESULT_DRAW == pkResultVo.getPkResult().intValue()) {
                        return;
                    }
                }
            }

            MqRequestMsg mqRequestMsg = new MqRequestMsg();
            mqRequestMsg.setTopic(MqConstants.UserMedalConsumer.USERE_MEDAL_TOPIC);
            mqRequestMsg.setTag(MqConstants.UserMedalConsumer.USER_MEDAL_TAGS);
            mqRequestMsg.setMsgId(String.valueOf(System.currentTimeMillis()));

            UserMedalMsg userMedalMsg = new UserMedalMsg();
            //栏目ID:足蓝网羽，必须与线上的categoryId保持一致
            userMedalMsg.setCategoryId(pkEventVo.getCategoryId());

            //当前用户ID
            userMedalMsg.setUid(uid);

            //个人勋章ID
            userMedalMsg.setMedalId(medalId);

            mqRequestMsg.setBody(ObjectUtil.toByteArray(userMedalMsg));

            MqResponse mqResponse = qcMsgClient.syncSend(mqRequestMsg);

            logger.info("userMedalMessage  mqSendStatus:"+mqResponse.getMqSendStatus());
        }catch (Exception e){
            logger.error("userMedalMsg  is failed. e:", e);
        }
    }

    private void clubMedalMessage(PKEventVo pkEventVo) {
        try {

            // 个人消息不推送
            if (pkEventVo.getType().byteValue() == GameConstants.TEAM_TYPE_PERSON) {
                return;
            }

            Integer medalId;
            Integer clubId = pkEventVo.getFromClub().getClubId();
            if (pkEventVo.getStatus().equals(PkEventStatusEnum.PK_STATUS_AGREE.getId())) {
                medalId = SysClubMedalConditionEnum.CHALLENGER.getId();
            } else if (pkEventVo.getStatus().equals(PkEventStatusEnum.PK_STATUS_CONFIRM.getId())) {
                medalId = SysClubMedalConditionEnum.CONQUEROR.getId();
                List<PKResultVo> pkResultVoList = bizPKEventDao.queryPkResultByPkid(pkEventVo.getId());
                for (PKResultVo pkResultVo : pkResultVoList) {
                    if (GameConstants.PK_RESULT_WIN == pkResultVo.getPkResult().intValue()) {
                        clubId = pkResultVo.getEntryId();
                    } else if (GameConstants.PK_RESULT_LOSE == pkResultVo.getPkResult().intValue()) {
                        clubId = pkEventVo.getFromClub().getClubId() == pkResultVo.getEntryId() ? pkEventVo.getToClub().getClubId() : pkEventVo.getFromClub().getClubId();
                    } else if (GameConstants.PK_RESULT_DRAW == pkResultVo.getPkResult().intValue()) {
                        return;
                    }
                }
            } else {
                return;
            }

            MqRequestMsg mqRequestMsg = new MqRequestMsg();
            mqRequestMsg.setTopic(MqConstants.ClubMedalConsumer.CLUB_MEDAL_TOPIC);
            mqRequestMsg.setTag(MqConstants.ClubMedalConsumer.CLUB_MEDAL_TAGS);
            mqRequestMsg.setMsgId(String.valueOf(System.currentTimeMillis()));

            ClubMedalMsg clubMedalMsg = new ClubMedalMsg();
            //栏目ID:足蓝网羽，必须与线上的categoryId保持一致
            clubMedalMsg.setCategoryId(pkEventVo.getCategoryId());

            //当前用户ID
            clubMedalMsg.setClubId(clubId);

            //俱乐部勋章ID
            clubMedalMsg.setMedalId(medalId);

            mqRequestMsg.setBody(ObjectUtil.toByteArray(clubMedalMsg));

            MqResponse mqResponse = qcMsgClient.syncSend(mqRequestMsg);

            logger.info("clubMedalMessage"+mqResponse.getMqSendStatus().toString());
        }catch (Exception e){
            logger.error("clubMedalMessage  is failed. e:", e);
        }
    }

    private void checkPkStatusAndProcess(PKEventVo pkEventVo, Integer id) {

        long begenTime = pkEventVo.getBeginTime().longValue() + 3600000L;
        if (pkEventVo.getStatus().equals(PkEventStatusEnum.PK_STATUS_CREATE.getId()) && checkBeginTime(pkEventVo.getBeginTime(),
                pkEventVo.getBeginTime1(),pkEventVo.getBeginTime2(), pkEventVo.getBeginTime3())) {

            updatePKStatus(pkEventVo.getId(), PkEventStatusEnum.PK_STATUS_EXPIRE.getId());
            pkEventVo.setStatus(PkEventStatusEnum.PK_STATUS_EXPIRE.getId());

        } else if (pkEventVo.getStatus().equals(PkEventStatusEnum.PK_STATUS_AGREE.getId()) && begenTime < System.currentTimeMillis()) {

            // 特殊处理（PK状态为已接受且PK已进行1个小时则Pk状态设置为已结束） begin
            logger.info("getPKInfoById updatePKStatus pk status update pk id:"+pkEventVo.getId()+" pkEventVo.getBeginTime:"+ begenTime);
            updatePKStatus(pkEventVo.getId(), PkEventStatusEnum.PK_STATUS_END.getId());
            pkEventVo.setStatus(PkEventStatusEnum.PK_STATUS_END.getId());

        } else if (pkEventVo.getStatus().equals( PkEventStatusEnum.PK_STATUS_ENTRY.getId())
                || pkEventVo.getStatus().equals(PkEventStatusEnum.PK_STATUS_CONFIRM.getId())) {

            // pk状态为已录完时，查询pk结果 begin
            List<PKResultVo> pkResultVoList = bizPKEventDao.queryPkResultByPkid(pkEventVo.getId());
            for (PKResultVo pkResultVo : pkResultVoList) {
                if (!id.equals(pkResultVo.getEntryId())) {
                    if (GameConstants.PK_RESULT_WIN == pkResultVo.getPkResult().intValue()) {
                        pkResultVo.setPkResult(GameConstants.PK_RESULT_LOSE);
                    } else if (GameConstants.PK_RESULT_LOSE == pkResultVo.getPkResult().intValue()) {
                        pkResultVo.setPkResult(GameConstants.PK_RESULT_WIN);
                    } else if (GameConstants.PK_RESULT_DRAW == pkResultVo.getPkResult().intValue()) {
                        pkResultVo.setPkResult(GameConstants.PK_RESULT_DRAW);
                    }
                }

                pkEventVo.setPkResultVo(pkResultVo);
            }
        }
    }
}